import { MerchantAPI, UploadAPI } from '../../utils/api'

interface ComboProduct {
  productId: number;
  productName?: string;
  imageUrl?: string;
  quantity: number;
  sortOrder?: number;
}

interface ComboFormData {
  mode: 'create' | 'edit';
  comboId: number | null;
  pageTitle: string;
  hasLogin: boolean;
  loading: boolean;
  uploading: boolean;
  showProductPicker: boolean;
  navBarHeight: number;
  scrollPaddingTop: string;
  comboForm: {
    name: string;
    description: string;
    imageUrl: string;
    marketPrice: string;
    regionPrice: string;
    sortOrder: string;
    products: ComboProduct[];
  };
  availableProducts: Array<{
    productId: number;
    productName: string;
    imageUrl: string;
    regionPrice: number;
    isSelected?: boolean;
  }>;
}

Page({
  data: {
    mode: 'create',
    comboId: null,
    pageTitle: '添加套餐',
    hasLogin: false,
    loading: false,
    uploading: false,
    showProductPicker: false,
    navBarHeight: 88,
    scrollPaddingTop: '118px',
    comboForm: {
      name: '',
      description: '',
      imageUrl: '',
      marketPrice: '',
      regionPrice: '',
      sortOrder: '1',
      products: []
    },
    availableProducts: []
  } as ComboFormData,

  onLoad(options: Record<string, string>) {
    const mode = options?.mode === 'edit' ? 'edit' : 'create';
    const comboId = options?.comboId ? Number(options.comboId) : null;
    this.setData({
      mode,
      comboId,
      pageTitle: mode === 'edit' ? '编辑套餐' : '添加套餐'
    });

    this.checkLoginStatus();
    // 立即计算一次，使用默认值
    this.calculateNavBarHeight();
    if (!this.data.hasLogin) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    this.initializeForm();
  },

  checkLoginStatus() {
    const token = wx.getStorageSync('merchantToken');
    const userInfo = wx.getStorageSync('merchantUserInfo');
    this.setData({
      hasLogin: Boolean(token && userInfo)
    });
  },

  calculateNavBarHeight() {
    setTimeout(() => {
      const query = wx.createSelectorQuery();
      query.select('.weui-navigation-bar__inner').boundingClientRect();
      query.exec((res: any) => {
        const navBarRect = res[0];
        if (navBarRect) {
          const navBarHeight = navBarRect.height;
          // 导航栏高度已经包含了状态栏和安全区域
          // 添加额外的安全边距30px，确保"套餐图片"字样和内容完全不被遮挡，同时最小化空白
          const contentPaddingTop = navBarHeight + 30;
          this.setData({
            navBarHeight: navBarHeight,
            scrollPaddingTop: `${contentPaddingTop}px`
          });
        } else {
          // 默认值：导航栏约88px（含状态栏），加上安全边距30px
          // 如果设备有安全区域，实际高度可能更高，所以给适当的默认值
          // 确保"套餐图片"字样完全可见，同时最小化空白
          this.setData({
            navBarHeight: 88,
            scrollPaddingTop: '118px'
          });
        }
      });
    }, 300); // 增加延迟，确保DOM完全渲染
  },

  async initializeForm() {
    try {
      if (this.data.mode === 'edit' && this.data.comboId) {
        await this.loadComboDetail(this.data.comboId);
      }
      await this.loadAvailableProducts();
    } catch (error) {
      console.error('初始化套餐表单失败', error);
    }
  },

  async loadComboDetail(comboId: number) {
    wx.showLoading({ title: '加载中...', mask: true });
    try {
      const detailRes = await MerchantAPI.getComboDetail(comboId);
      const detail = detailRes?.data || {};
      const products: ComboProduct[] = Array.isArray(detail.products)
        ? detail.products.map((item: any, index: number) => ({
            productId: item.productId || item.dishId || 0,
            productName: item.productName || item.dishName || item.name || '',
            imageUrl: item.imageUrl || item.images?.[0] || '',
            quantity: item.quantity || 1,
            sortOrder: item.sortOrder ?? index
          }))
        : [];

      this.setData({
        comboForm: {
          name: detail.name || '',
          description: detail.description || '',
          imageUrl: detail.imageUrl || '',
          marketPrice: String(detail.marketPrice ?? 0),
          regionPrice: String(detail.regionPrice ?? 0),
          sortOrder: String(detail.sortOrder ?? '1'),
          products
        }
      });
    } catch (error) {
      console.error('获取套餐详情失败', error);
      wx.showToast({ title: '加载详情失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },

  async loadAvailableProducts() {
    try {
      const response = await MerchantAPI.getProducts({
        pageNum: 1,
        pageSize: 100,
        status: 1
      });
      const rows = response?.rows || response?.data?.rows || [];
      const selectedIds = this.data.comboForm.products.map(p => p.productId);
      const products = rows.map((item: any) => {
        const productId = item.productId || item.dishId || 0;
        return {
          productId,
          productName: item.name || item.dishName || item.productName || '',
          imageUrl: item.imageUrl || item.images?.[0] || '/images/empty-messages.png',
          regionPrice: Number(item.regionPrice ?? item.price ?? 0),
          isSelected: selectedIds.includes(productId)
        };
      });
      this.setData({ availableProducts: products });
    } catch (error) {
      console.error('加载商品列表失败', error);
      wx.showToast({ title: '商品加载失败', icon: 'none' });
    }
  },

  onFormInput(e: any) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    if (!field) return;
    this.setData({
      [`comboForm.${field}`]: value
    });
  },

  updateProductQuantity(e: any) {
    const index = e.currentTarget.dataset.index;
    const value = Math.max(1, Number(e.detail.value) || 1);
    const products = [...this.data.comboForm.products];
    if (products[index]) {
      products[index].quantity = value;
      this.setData({ 'comboForm.products': products });
    }
  },

  removeComboProduct(e: any) {
    const index = e.currentTarget.dataset.index;
    const products = [...this.data.comboForm.products];
    const removed = products.splice(index, 1)[0];
    products.forEach((p, idx) => (p.sortOrder = idx));
    const updatedAvailable = this.data.availableProducts.map(p => ({
      ...p,
      isSelected: removed && p.productId === removed.productId ? false : p.isSelected
    }));
    this.setData({
      'comboForm.products': products,
      availableProducts: updatedAvailable
    });
  },

  async openProductPicker() {
    if (this.data.availableProducts.length === 0) {
      await this.loadAvailableProducts();
    }
    this.setData({ showProductPicker: true });
  },

  closeProductPicker() {
    this.setData({ showProductPicker: false });
  },

  selectProduct(e: any) {
    const productId = Number(e.currentTarget.dataset.id);
    const target = this.data.availableProducts.find(p => p.productId === productId);
    if (!target) return;

    const exists = this.data.comboForm.products.find(p => p.productId === productId);
    if (exists) {
      wx.showToast({ title: '该商品已添加', icon: 'none' });
      return;
    }

    const products = [...this.data.comboForm.products, {
      productId: target.productId,
      productName: target.productName,
      imageUrl: target.imageUrl,
      quantity: 1,
      sortOrder: this.data.comboForm.products.length
    }];

    const availableProducts = this.data.availableProducts.map(p => ({
      ...p,
      isSelected: p.productId === productId ? true : p.isSelected
    }));

    this.setData({
      'comboForm.products': products,
      availableProducts,
      showProductPicker: false
    });
  },

  async chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: async (res) => {
        const path = res.tempFilePaths[0];
        if (!path) return;
        this.setData({ uploading: true });
        wx.showLoading({ title: '上传中...' });
        try {
          const uploadRes = await UploadAPI.uploadFile(path);
          console.log('套餐图片上传响应数据:', uploadRes);
          // 后端返回格式: { code: 200, msg: "操作成功", data: "https://xxx.com/xxx.png" }
          // 优先使用 data 字段（可能是字符串URL），其次是 data.url 等字段
          let url = '';
          if (uploadRes?.data) {
            if (typeof uploadRes.data === 'string') {
              // data 直接是 URL 字符串
              url = uploadRes.data;
            } else if (uploadRes.data.url) {
              // data 是对象，包含 url 字段
              url = uploadRes.data.url;
            } else if (uploadRes.data.fileUrl) {
              url = uploadRes.data.fileUrl;
            } else if (uploadRes.data.fileName) {
              url = uploadRes.data.fileName;
            }
          }
          if (!url) {
            url = uploadRes?.url || path;
          }
          console.log('套餐图片最终使用的URL:', url);
          this.setData({
            'comboForm.imageUrl': url
          });
        } catch (error) {
          console.error('图片上传失败', error);
          wx.showToast({ title: '上传失败', icon: 'none' });
        } finally {
          this.setData({ uploading: false });
          wx.hideLoading();
        }
      }
    });
  },

  async submitComboForm() {
    const { comboForm, mode, comboId } = this.data;

    if (!comboForm.name.trim()) {
      wx.showToast({ title: '请输入套餐名称', icon: 'none' });
      return;
    }
    if (!comboForm.regionPrice || Number(comboForm.regionPrice) <= 0) {
      wx.showToast({ title: '请输入正确的售价', icon: 'none' });
      return;
    }
    if (!comboForm.marketPrice || Number(comboForm.marketPrice) <= 0) {
      wx.showToast({ title: '请输入正确的市场价', icon: 'none' });
      return;
    }
    if (comboForm.products.length === 0) {
      wx.showToast({ title: '请至少添加一个商品', icon: 'none' });
      return;
    }

    for (const product of comboForm.products) {
      if (!product.quantity || product.quantity < 1) {
        wx.showToast({ title: `${product.productName || '商品'}份数需大于0`, icon: 'none' });
        return;
      }
    }

    this.setData({ loading: true });
    wx.showLoading({ title: '保存中...', mask: true });

    try {
      const payload: any = {
        name: comboForm.name.trim(),
        description: comboForm.description || '',
        imageUrl: comboForm.imageUrl || '',
        marketPrice: Number(comboForm.marketPrice),
        regionPrice: Number(comboForm.regionPrice),
        sortOrder: Number(comboForm.sortOrder) || 1,
        products: comboForm.products.map((p, index) => ({
          productId: p.productId,
          quantity: p.quantity,
          sortOrder: p.sortOrder ?? index
        }))
      };

      if (mode === 'edit' && comboId) {
        payload.comboId = comboId;
        await MerchantAPI.updateCombo(payload);
        wx.showToast({ title: '更新成功', icon: 'success' });
      } else {
        await MerchantAPI.createCombo(payload);
        wx.showToast({ title: '创建成功', icon: 'success' });
      }

      wx.setStorageSync('combos_should_refresh', true);
      setTimeout(() => {
        wx.navigateBack();
      }, 400);
    } catch (error: any) {
      console.error('保存套餐失败', error);
      wx.showToast({
        title: error?.message || error?.msg || '保存失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
      this.setData({ loading: false });
    }
  },

  handleCancel() {
    wx.navigateBack();
  },

  noop() {}
})


